using RedPoint.Runtime;
using UnityEditor.IMGUI.Controls;

namespace Framework.RedPoint.Editor {
    /// <summary>
    /// 红点树视图
    /// </summary>
    public class ReddotTreeView :  TreeView
    {
        private ReddotTreeViewItem m_Root;

        private int m_curID;
        
        public ReddotTreeView(TreeViewState state) : base(state)
        {
            Reload();
            
            useScrollView = true;
            
            RedPointManager.Instance.NodeNumChangeCallback += Reload;
            RedPointManager.Instance.NodeValueChangeCallback += Repaint;
        }
        
        protected override TreeViewItem BuildRoot()
        {
            m_curID = 0;

            m_Root = PreOrder(RedPointManager.Instance.Root);
            m_Root.depth = -1;
            
            SetupDepthsFromParentsAndChildren(m_Root);
            
            return m_Root;
        }
        
        /// 重绘函数，不会进行重新构建BuildRoot
        /// 而是调用Item的OnGUI
        private void Repaint(PointNode node, int value)
        {
            Repaint();
        }

        /// <summary>
        /// 前序遍历创建
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        private ReddotTreeViewItem PreOrder(PointNode node)
        {
            if (node == null) return null;
            
            ReddotTreeViewItem item = new ReddotTreeViewItem(m_curID++, node);

            if (node.ChildrenCount > 0)
            {
                foreach (var child in node.Childrens)
                {
                    item.AddChild(PreOrder(child));
                }
            }

            return item;
        }
        
        
        public void OnDestory()
        {
            RedPointManager.Instance.NodeNumChangeCallback -= Reload;
            RedPointManager.Instance.NodeValueChangeCallback -= Repaint;
        }
        
    }
}